package com.cloud.pole.admin.config;

import java.util.ArrayList;
import java.util.Collections;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.cloud.pole.common.handler.GlobalExceptionHandler;
import com.cloud.pole.common.interceptor.AdminAuthRestInterceptor;
import com.cloud.pole.common.interceptor.ServiceAuthRestInterceptor;
import com.cloud.pole.common.interceptor.UserAuthRestInterceptor;

@Configuration("admimWebConfig")
@Primary
public class WebConfiguration extends WebMvcConfigurerAdapter {
	@Bean
	GlobalExceptionHandler getGlobalExceptionHandler() {
		return new GlobalExceptionHandler();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 客户端调用需要过滤的(需要过滤token和client-token)
		/*网关上增加了参数client-token，防止从微服务端口直接访问*/
		registry.addInterceptor(getServiceAuthRestInterceptor())
				.addPathPatterns(getClientPathPatterns().toArray((new String[] {})))
				.addPathPatterns(getAdminPathPatterns().toArray(new String[] {}));

		// 后台调用需要过滤
		registry.addInterceptor(getAdminAuthRestInterceptor()).addPathPatterns(getAdminPathPatterns().toArray(new String[] {}));
	}

	@Bean
	ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
		return new ServiceAuthRestInterceptor();
	}

	@Bean
	UserAuthRestInterceptor getUserAuthRestInterceptor() {
		return new UserAuthRestInterceptor();
	}

	@Bean
	AdminAuthRestInterceptor getAdminAuthRestInterceptor() {
		return new AdminAuthRestInterceptor();
	}
	
	/**
	 * 需要用户和服务认证判断的路径 （后台地址）
	 * 
	 * @return
	 */
	private ArrayList<String> getAdminPathPatterns() {
		ArrayList<String> list = new ArrayList<>();
		String[] urls = { "/element/**", "/gateLog/**", "/group/**", "/groupType/**", "/menu/**", "/user/**"
		};
		Collections.addAll(list, urls);
		return list;
	}
	

	/**
	 * 需要用户和服务认证判断的路径(客户端)
	 * 
	 * @return
	 */
	private ArrayList<String> getClientPathPatterns() {
		ArrayList<String> list = new ArrayList<>();
		String[] urls = { "/api/permissions",
						  "/api/user/un/**",
						  "/api/user/validate",
						  "/api/log/save",
						  "/rest/user/getUser"
							};
		Collections.addAll(list, urls);
		return list;
	}
}
